package com.damozan.iossupersign.service.Ipapackage.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.plist.NSDictionary;
import com.dd.plist.PropertyListParser;
import com.damozan.iossupersign.config.DomainConfig;
import com.damozan.iossupersign.enums.ServiceError;
import com.damozan.iossupersign.exception.ServiceException;
import com.damozan.iossupersign.model.bo.IpaPackageBO;
import com.damozan.iossupersign.model.po.IpaPackagePO;
import com.damozan.iossupersign.service.Ipapackage.IpaPackageBSService;
import com.damozan.iossupersign.service.Ipapackage.IpaPackageService;
import com.damozan.iossupersign.service.file.FileService;
import com.damozan.iossupersign.service.udid.UDIDBSService;
import com.damozan.iossupersign.utils.FileUtils;
import com.damozan.iossupersign.utils.IosUrlUtils;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Peter.Hong
 * @date 2019/12/11
 */
@Service
@Slf4j
public class IpaPackageBSServiceImpl implements IpaPackageBSService {

    private static final String FILE_NAME_SPLIT = ".";

    private static final String FILE_NAME = "ipa";

    private static final Long DEFAULT_PAGE_SIZE = 20L;

    private final IpaPackageService ipaPackageService;

    private final FileService fileService;

    private final DomainConfig domainConfig;

    private final UDIDBSService udidbsService;

    @Value("${file.ipaUploadPath}")
    private String fileUploadPath;

    @Autowired
    public IpaPackageBSServiceImpl(IpaPackageService ipaPackageService, FileService fileService, DomainConfig domainConfig, UDIDBSService udidbsService) {
        this.ipaPackageService = ipaPackageService;
        this.fileService = fileService;
        this.domainConfig = domainConfig;
        this.udidbsService = udidbsService;
    }

    @Override
    public void uploadIpa(IpaPackageBO ipaPackageBO) {

        String fileName = ipaPackageBO.getFile().getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(FILE_NAME_SPLIT) + 1);
        if (suffix.equalsIgnoreCase(FILE_NAME)) {
           
        }else {
            // 上传的文件非ipa文件
            // throws exception
            log.error("file is not ipa");
            throw new ServiceException(ServiceError.INVALID_PARAMETER);
        }
    }

    @Override
    public Page<IpaPackagePO> selectIpaByName(@NotNull Integer currentPage, String name) {

        Page<IpaPackagePO> page = new Page<>();
        page.setCurrent(currentPage.longValue());
        page.setSize(DEFAULT_PAGE_SIZE);
        page = ipaPackageService.getIpaPackagePage(page, name);

        if(!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().forEach(packagePO -> {
                packagePO.setDownloadUrl(IosUrlUtils.getUdidViewUrl(domainConfig.getIpaUrlPath(),packagePO.getIpaDownloadId()));
            });
        }
        return page;
    }

    @Override
    public IpaPackagePO selectIpaByDownloadId(@NotNull String downloadId) {
        return ipaPackageService.selectByDownloadId(downloadId);
    }

    private IpaPackagePO analyze(IpaPackageBO ipaPackageBO) throws Exception{
        MultipartFile file =  ipaPackageBO.getFile();
        String summary = ipaPackageBO.getSummary();
        File excelFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), ".ipa");
        log.info("ipa文件上传excelFile="+excelFile.getAbsolutePath());
        
        file.transferTo(excelFile);
        File ipa = ZipUtil.unzip(excelFile);
        File app = getAppFile(ipa);
        File info = new File(app.getAbsolutePath()+"/Info.plist");
        NSDictionary parse = (NSDictionary) PropertyListParser.parse(new FileReader(info).readBytes());
        String name = parse.get("CFBundleName").toString();
        if (parse.containsKey("CFBundleDisplayName")) {
            name = parse.get("CFBundleDisplayName").toString();
        }
        String version = parse.get("CFBundleShortVersionString").toString();
        String buildVersion = parse.get("CFBundleVersion").toString();
        String miniVersion = parse.get("MinimumOSVersion").toString();
        String bundleIdentifier = parse.get("CFBundleIdentifier").toString();

        String ipaDownloadId = DigestUtils.md5DigestAsHex(bundleIdentifier.getBytes());

        String pathname = fileUploadPath +"/"+ipaDownloadId+"/"+ ipaDownloadId+".ipa";
        log.info("ipa文件上传pathname="+pathname);
        
        String appLink = fileService.uploadFile(excelFile, pathname);
        if (appLink != null) {
            log.info("ipa文件上传完成");
        }

        
        NSDictionary icons = null;
        if (parse.containsKey("CFBundleIcons")) {
            icons = (NSDictionary) parse.get("CFBundleIcons");
        }else if (parse.containsKey("CFBundleIcons~ipad")) {
            icons = (NSDictionary) parse.get("CFBundleIcons~ipad");
        }
        String iconLink = null;
        if (icons != null && icons.toJavaObject()!=null && icons.get("CFBundlePrimaryIcon")  != null ) {
            List<?> list = ((NSDictionary) icons.get("CFBundlePrimaryIcon")).get("CFBundleIconFiles").toJavaObject(List.class);
            iconLink = (String) list.get(list.size()-1);
            String iconPath = app.getAbsolutePath() + "/" + iconLink;
            File icon = new File( iconPath + "@3x.png");
            if (!icon.exists()) {
                icon = new File(iconPath+"@2x.png");
            }
            iconLink = uploadIcon(icon,ipaDownloadId);
            icon.delete();
        }
        
        
        String mobileFileName =ipaDownloadId+"/"+ ipaDownloadId+".mobileconfig";

        return IpaPackagePO.builder()
                .id(ipaPackageBO.getId())
                .name(name)
                .icon(iconLink)
                .version(version)
                .buildVersion(buildVersion)
                .miniVersion(miniVersion)
                .bundleIdentifier(bundleIdentifier)
                .link(appLink)
                .summary(summary)
                .ipaDownloadId(ipaDownloadId)
                .mobileFileName(mobileFileName)
                .build();
    }

    String uploadIcon(File file,String ipaDownloadId) {
        String pathname = ipaDownloadId +File.separator+ "appicon.png";
        try {
			fileService.uploadFile(file,  fileUploadPath + File.separator + pathname);
		} catch (IOException e) { 
		}
        
        return  "/upload/"+ pathname;
    }

    
    private File getAppFile(File ipaFile) {
        File payload = new File(ipaFile.getAbsolutePath() + "/Payload/");
        if (payload != null) {
            for (File file : payload.listFiles()) {
                if (FileUtils.getSuffixName(file).equalsIgnoreCase("app")) {
                    return file;
                }
            }
        }
        return null;
    }

}
